package hlhj.fhp.checkpoint.atys

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import com.alipay.sdk.app.PayTask
import com.google.gson.Gson
import hlhj.fhp.checkpoint.BaseAty
import hlhj.fhp.checkpoint.R
import hlhj.fhp.checkpoint.iview.PayView
import hlhj.fhp.checkpoint.javaBean.AliPayBean
import hlhj.fhp.checkpoint.javaBean.MyBaseBean
import hlhj.fhp.checkpoint.presenter.PayPresenter
import kotlinx.android.synthetic.main.aty_pay.*
import kotlinx.android.synthetic.main.lo_pub_head.*
import android.widget.Toast
import com.example.mymvp.log
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import hlhj.fhp.checkpoint.Constant
import hlhj.fhp.checkpoint.iview.ActiveView
import hlhj.fhp.checkpoint.javaBean.WxPayBean
import hlhj.fhp.checkpoint.javaBean.WxPaySuccessEvent
import hlhj.fhp.checkpoint.presenter.ActivePresenter
import hlhj.fhp.checkpoint.utils.ToastUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * Created by Never Fear   on 2018\11\26 0026.
Never More....
 */
class PayAty :BaseAty<PayView,PayPresenter>(), PayView, ActiveView {
    private var oid="-1"//订单ID
    private var money:String?="0"//金额
    private var offer:String?="0"//服务费
    private var payType =0//0-微信 1-支付宝
    private var orderType=0 //0年检 1//违章 2//激活
    private var api: IWXAPI? = null
    private var activePresenter:ActivePresenter?=null

    private val mHandler= @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val result = msg!!.obj as Map<String, String>
            log("fhp","回调为${result.toString()}")
            val status = result["resultStatus"]
            if (status.equals("9000")){
                Constant.isActive=true
                ToastUtils.toast("支付成功",this@PayAty)
                setResult(-1)
                finish()
            }else{

            }
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    override fun initView() {
        EventBus.getDefault().register(this)
        api = WXAPIFactory.createWXAPI(this, Constant.WXAPPID,true)
        api!!.registerApp(Constant.WXAPPID)
        tvTittle.text="支付"
        oid=intent.getStringExtra("id")
        money =intent.getStringExtra("money")
        offer=intent.getStringExtra("offer")
        orderType=intent.getIntExtra("orderType",-1)
        money?.let {
            tvPrice.text=money
        }
        offer?.let {
            tvOffer.text="(含服务费${offer}元)"
        }

        when(orderType){
            0->{
                tvOrder.text="违章订单"
            }
            1->{
                tvOrder.text="年检订单"
            }
            2->{
                tvOrder.text="激活用户"
            }
        }


    }

    override fun setPayResult(myBaseBean: MyBaseBean) {
    }

    override fun logicStart() {

    }

    override fun setListener() {
        btPay.setOnClickListener {
            when(orderType){
                0->{
                    presenter?.violationPay(oid,payType,this@PayAty)
                }
                1->{
                    presenter?.yearPay(oid,payType,this@PayAty)
                }
                2->{
                    activePresenter?.getActiveOrderSign(payType,this@PayAty)
                }
            }

        }
        cbWx.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked){
                cbAli.isChecked=false
                payType=0
            }
        }
        cbAli.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked){
                cbWx.isChecked=false
                payType=1
            }
        }
    }

    private val SDK_PAY_FLAG: Int=1010

    override fun setYearPayOrderSign(string: String) {
        try {
            if (payType==1){
                val payBean = Gson().fromJson(string, AliPayBean::class.java)
                val orderInfo = payBean.info   // 订单信息

                val payRunnable = Runnable {
                    val alipay = PayTask(this)
                    val result = alipay.payV2(orderInfo, true)

                    val msg = Message()
                    msg.what = SDK_PAY_FLAG
                    msg.obj = result
                    mHandler.sendMessage(msg)
                }
                // 必须异步调用
                val payThread = Thread(payRunnable)
                payThread.start()
            }else if (payType==0){
                val data = Gson().fromJson(string, WxPayBean::class.java).info
                val req = PayReq()
                req.appId=data.appid
                req.partnerId = data.partnerid
                req.prepayId = data.prepayid
                req.nonceStr = data.noncestr
                req.timeStamp = data.timestamp.toString()
                req.packageValue = data.packageX
                req.sign = data.sign
                req.extData="支付界面"
                api!!.sendReq(req)
            }
        }catch (e:Exception){
            e?.printStackTrace()
        }

    }

    override fun setViolationPayOrderSign(string: String) {
        try {
            if (payType==1){
                val payBean = Gson().fromJson(string, AliPayBean::class.java)
                val orderInfo = payBean.info   // 订单信息

                val payRunnable = Runnable {
                    val alipay = PayTask(this)
                    val result = alipay.payV2(orderInfo, true)

                    val msg = Message()
                    msg.what = SDK_PAY_FLAG
                    msg.obj = result
                    mHandler.sendMessage(msg)
                }
                // 必须异步调用
                val payThread = Thread(payRunnable)
                payThread.start()
            }
            else if (payType==0){
                val data = Gson().fromJson(string, WxPayBean::class.java).info
                val req = PayReq()
                req.appId=data.appid
                req.partnerId = data.partnerid
                req.prepayId = data.prepayid
                req.nonceStr = data.noncestr
                req.timeStamp = data.timestamp.toString()
                req.packageValue = data.packageX
                req.sign = data.sign
                req.extData="支付界面"
                api!!.sendReq(req)
            }
        }catch (e:Exception){
            e?.printStackTrace()
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun wxpaySuccess(event:WxPaySuccessEvent){
        setResult(-1)
        finish()
    }
    override fun setActiveOrderSign(beanStr: String) {
        if (payType==0){
            val data = Gson().fromJson(beanStr, WxPayBean::class.java).info
            val req = PayReq()
            req.appId=data.appid
            req.partnerId = data.partnerid
            req.prepayId = data.prepayid
            req.nonceStr = data.noncestr
            req.timeStamp = data.timestamp.toString()
            req.packageValue = data.packageX
            req.sign = data.sign
            req.extData="激活用户"
            api!!.sendReq(req)
        }else if (payType==1){
            val payBean = Gson().fromJson(beanStr, AliPayBean::class.java)
            val orderInfo = payBean.info   // 订单信息

            val payRunnable = Runnable {
                val alipay = PayTask(this)
                val result = alipay.payV2(orderInfo, true)

                val msg = Message()
                msg.what = SDK_PAY_FLAG
                msg.obj = result
                mHandler.sendMessage(msg)
            }
            // 必须异步调用
            val payThread = Thread(payRunnable)
            payThread.start()
        }

    }
    override fun bindView(): PayView {
        return this
    }



    override fun createPresenter(): PayPresenter {
        activePresenter= ActivePresenter()
        activePresenter?.createModule()
        activePresenter?.bindView(this)
        return PayPresenter()
    }

    override val contentId: Int= R.layout.aty_pay
}